//
//  ACHdb.m
//  MansApp
//
//  Created by lanou3g on 15/7/27.
//  Copyright (c) 2015年 ACH. All rights reserved.
//

#import "ACHdb.h"
#import "FMDB.h"

#define tableName @"MyNoteBook"
@implementation ACHdb

static FMDatabase *_db = nil;

 



-(NSString*)documentsPath:(NSString*)dbName{
    
    NSString *nameA = [NSString stringWithFormat:@"%@.db",dbName];

    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:nameA];
}



+(ACHdb*)sharedInstance{
    
    static ACHdb *myDB = nil;
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        myDB = [[ACHdb alloc]init];
        
        
    });
    
    
    return myDB;
}


- (void)achDB{
    if (!_db) {
   _db = [FMDatabase databaseWithPath:[self documentsPath:@"ACHDB"]];
  
    }
    
    
}
-(void)createTable{
    
    [self achDB];
    
    if ([_db open]) {
        
        NSString *sqlCreateTable = [NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS %@ (ID integer primary key autoincrement,date text not null unique ,diaryname text,diary blob,motif text,tape text,picarray blob)",tableName];
        
        
        BOOL b = [_db executeUpdate:sqlCreateTable];
        if (b) {
            NSLog(@"建表成功");
        }
        else {
            NSLog(@"建表失败");
        }
        
    }
    
    
    
}





- (NSMutableArray*)showTheTableAll{
    NSMutableArray *array = [NSMutableArray array];
    [array addObject:[NSMutableArray array]];
    [array addObject:[NSMutableArray array]];
    [self achDB];
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"select *from %@ order by date desc",tableName];
        FMResultSet *rs = [_db executeQuery:sql];
      
        while ([rs next]) {
            
            NSString *date = [rs stringForColumn:@"date"];
            [array.firstObject addObject:date];
            NSString *diaryName = [rs stringForColumn:@"diaryname"];
            
            if (!diaryName || diaryName.length == 0) {
                diaryName = @"";
            }
            
            [array.lastObject addObject:diaryName];
            
        }
        
        
        
        
        
        [_db close];
    }
    return array;
    
}

- (NSMutableArray*)showTheAllTape{
 NSMutableArray *array = [NSMutableArray array];
    [self achDB];
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"select *from %@ ",tableName];
        FMResultSet *rs = [_db executeQuery:sql];
        
        while ([rs next]) {
            
            
            
            NSString *tape = [rs stringForColumn:@"tape"];
            [array addObject:tape];
         
            
        }
        
        [_db close];
    }
    return array;
    


}
- (DiaryModel *)showOneWithDate:(NSString *)date{
    [self achDB];
    
    
    DiaryModel *diary = [[DiaryModel alloc]init];
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"select *from %@ where date = ?",tableName];
        FMResultSet *rs = [_db executeQuery:sql,date];
        while ([rs next]) {
            
            diary.diary = [self unarchiverData:[rs dataForColumn:@"diary"] andKey:@"AttributedString"];
         
            diary.diaryName = [rs stringForColumn:@"diaryname"];
            diary.motif = [rs stringForColumn:@"motif"];
            diary.date = [rs stringForColumn:@"date"];
            diary.tape= [rs stringForColumn:@"tape"];
            diary.picArray = [self unarchiverData:[rs dataForColumn:@"picarray"] andKey:@"picArray"];
            
            
            
        }
        [_db close];
        
    }
    
    return diary;
}




- (void)insertDate:(NSString*)date{
 FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self documentsPath:@"ACHDB"]];
        
        [queue inDatabase:^(FMDatabase *db) {   
       [self achDB];
    if ([db open]) {
        
        
        NSString *sql = [NSString stringWithFormat:@"insert into %@(date) values(?)",tableName];
        BOOL b = [db executeUpdate:sql,date];
        
        if (b) {
            NSLog(@"插入成功");
        }
        else{
            
            NSLog(@"插入失败");
        }
       
        [db close];
        
    }
 }];
 
}







- (void)updataWithDate:(NSString*)date upDiary:(NSAttributedString *)diary{

    [self achDB];
    
    if ([_db open]) {
        
        
    
        NSMutableData *data = [self dataArchiverWithObject:diary andKey:@"AttributedString"];
       NSString *sql = [NSString stringWithFormat:@"update %@ set diary = ?  where date = ?",tableName];
       BOOL b = [_db executeUpdate:sql,data,date];
        
        if (b) {
            NSLog(@"富文本存储成功");
        }
        else{
            
            NSLog(@"富文本存储失败");
        }

        
        
        
        [_db close];
    }
    
    
    
    
}



-(void)updataWithDate:(NSString*)date upDiaryName:(NSString *)diaryName{
    
    [self achDB];
    
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"update %@ set diaryname = ?  where date = ?",tableName];
    BOOL b=    [_db executeUpdate:sql,diaryName,date];
        if (b) {
            NSLog(@"更新 表名成功");
        }
        else{
            
            NSLog(@"更新 表名失败");
        }

        
        
        [_db close];
    }
}

-(void)updataWithDate:(NSString*)date upMotif:(NSString *)motif{
   FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self documentsPath:@"ACHDB"]];
        
        [queue inDatabase:^(FMDatabase *db) {  
    [self achDB];
    
    if ([db open]) {
        
       
        NSString *sql = [NSString stringWithFormat:@"update %@ set motif = ?  where date = ?",tableName];
      BOOL b =   [db executeUpdate:sql,motif,date];
        if (b) {
            NSLog(@"更新 主题成功");
        }
        else{
            
            NSLog(@"更新 主题失败");
        }
        
        
        
        [db close];
    }
        }];
}

-(void)updataWithDate:(NSString*)date upTape:(NSString *)tape{
    
    [self achDB];
    
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"update %@ set tape = ?  where date = ?",tableName];
        BOOL b =   [_db executeUpdate:sql,tape,date];
        if (b) {
            NSLog(@"更新 录音文件");
        }
        else{
            
            NSLog(@"更新 录音文件");
        }
        
        
        
        [_db close];
    }
}


-(void)updataWithDate:(NSString*)date upNewDate:(NSString *)newDate{
         FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self documentsPath:@"ACHDB"]];
        
        [queue inDatabase:^(FMDatabase *db) {
    [self achDB];
    
    if ([db open]) {
   
        NSString *sql = [NSString stringWithFormat:@"update %@ set date = ?  where date = ?",tableName];
        BOOL b =   [db executeUpdate:sql,newDate,date];
        if (b) {
            NSLog(@"更新 日期成功");
        }
        else{
            
            NSLog(@"更新 日期失败");
        }
        
        
        
        [db close];
    }
        }];
}

-(void)updataWithDate:(NSString*)date upPicArray:(NSMutableArray *)picArray{
    
    [self achDB];
    
    if ([_db open]) {
        
        NSString *sql = [NSString stringWithFormat:@"update %@ set picarray = ?  where date = ?",tableName];
        
        NSMutableData *data = [self dataArchiverWithObject:picArray andKey:@"picArray"];
        BOOL b=    [_db executeUpdate:sql,data,date];
        if (b) {
            NSLog(@"更新 图片组成功");
        }
        else{
            
            NSLog(@"更新 图片组失败");
        }
        
        
        
        [_db close];
    }
}

-(void)upDatawithDate:(NSString *)date wtihDiary:(NSAttributedString *)diary diaryName:(NSString *)diaryName tape:(NSString *)tape picArray:(NSMutableArray*)picArray{
     FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self documentsPath:@"ACHDB"]];
        
         [queue inDatabase:^(FMDatabase *db) {
    [self achDB];
    if ([db open]) {
       
        
        NSString *sql = [NSString stringWithFormat:@"update %@ set diary = ?,diaryname = ?,tape = ?,picarray = ?  where date = ?",tableName];
        NSMutableData *dataDiary = [self dataArchiverWithObject:diary andKey:@"AttributedString"];
        
        
        NSMutableData *dataPic = [self dataArchiverWithObject:picArray andKey:@"picArray"];
        

        BOOL b = [db executeUpdate:sql,dataDiary,diaryName,tape,dataPic,date];
        if (b) {
            NSLog(@"更新  数据成功");
        }
        else{
            
            NSLog(@"更新 数据失败");
        }
        
        
        
        [db close];
    }
 
    
     }];
    
}



- (void)deleteWithDate:(NSString*)date{
    
    FMDatabaseQueue *queue = [FMDatabaseQueue databaseQueueWithPath:[self documentsPath:@"ACHDB"]];
    [queue inDatabase:^(FMDatabase *db) {
        
    
        
    [self achDB];
        
        
      
        
        
    if ([db open]) {
        
    
        
        
        NSString *sql = [NSString stringWithFormat:@"select *from %@ where date = ?",tableName];
        NSString *tape ;
        FMResultSet *rs = [db executeQuery:sql,date];
        while ([rs next]) {
            tape= [rs stringForColumn:@"tape"];
            NSLog(@"%@",tape);
        }
        if (tape && tape.length != 0) {
        NSMutableArray *arrayA =[NSMutableArray arrayWithArray:[tape  componentsSeparatedByString:@"/"]];
        [arrayA removeObject:@""];
        NSLog(@"%@",arrayA);
        NSFileManager *manager = [NSFileManager defaultManager];
        
        [arrayA enumerateObjectsUsingBlock:^(NSString  *obj, NSUInteger idx, BOOL *stop) {
            
            
            if( [manager  fileExistsAtPath:[self byAppendingForCache:obj]]){
                
                [manager removeItemAtPath:[self byAppendingForCache:obj] error:nil];
            };
            
        }];
        
       }
        
        
        
        
        
        
        NSString *sql1 = [NSString stringWithFormat:@"delete from %@ where date = ?",tableName];
        
        BOOL b = [db executeUpdate:sql1,date];
        if (b) {
            NSLog(@"删除成功");
        }
        else {
            
            NSLog(@"删除失败");
        }
        
        [db close];
    }
    
    }];
}


- (NSMutableData*)dataArchiverWithObject:(id<NSCoding>)object andKey:(NSString*)key{
    
    NSMutableData *data = [NSMutableData data];
    
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc]initForWritingWithMutableData:data];
    
    [archiver encodeObject:object forKey:key];
    
    [archiver finishEncoding];
    
    
    return data;
    
    
}

- (id)unarchiverData:(NSData*)data andKey:(NSString*)key{
    
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc]initForReadingWithData:data];
    
    id obj =[unarchiver decodeObjectForKey:key];
    [unarchiver finishDecoding];
    
    return obj;
    
    
}
- (NSString *)byAppendingForCache:(NSString *)str{
    
    NSString *myCachePath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject;
    
    return [NSString stringWithFormat:@"%@/%@",myCachePath,str];
}
@end
